#include"Stack_realloc.h"

// 初始化栈 
void StackInit(Stack* ps)
{
	ps->_a = (STDataType*)malloc(sizeof(STDataType) * 10);
	if (ps->_a == NULL)
	{
		perror("malloc error");
		return;
	}

	ps->_top = -1;
	ps->_capacity = 10;
}

// 动态扩展栈的容量
void StackGrow(Stack* ps)
{
	int new_capacity = ps->_capacity * 2;
	STDataType* new_a = (STDataType*)realloc(ps->_a, sizeof(STDataType) * new_capacity);
	if (new_a == NULL)
	{
		perror("realloc error");
		return;
	}

	ps->_a = new_a;
	ps->_capacity = new_capacity;
}


// 入栈 
void StackPush(Stack* ps, STDataType data)
{
	if (ps->_top == ps->_capacity - 1)
	{
		StackGrow(ps);
	}
	ps->_a[++ps->_top] = data;
}
// 出栈 
void StackPop(Stack* ps)
{
	if (StackEmpty(ps))
	{
		printf("The Stack is empty!");
		return;
	}

	ps->_top--;
}
// 获取栈顶元素 
STDataType StackTop(Stack* ps)
{
	if (StackEmpty(ps))
	{
		printf("The Stack is empty!");
		return;
	}

	return ps->_a[ps->_top];
}
// 获取栈中有效元素个数 
int StackSize(Stack* ps)
{
	return ps->_top + 1;
}
// 检测栈是否为空，如果为空返回非零结果，如果不为空返回0 
int StackEmpty(Stack* ps)
{
	return ps->_top == -1;
}
// 销毁栈 
void StackDestroy(Stack* ps)
{
	free(ps->_a);
	ps->_a = NULL;
	ps->_capacity = 0;
	ps->_top = -1;
}